﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace TeamDoer.Controllers
{
	[Authorize]
    public class TasksController : BaseController
	{
		private Models.TaskService _taskService;

		protected override void Initialize(System.Web.Routing.RequestContext requestContext)
		{
			base.Initialize(requestContext);

			if(User.Identity.IsAuthenticated)
				_taskService = new Models.TaskService(User.Identity.Name);
		}

        //
        // GET: /Tasks/

        public ActionResult Index()
        {
			var taskLists = new Models.TaskListsGridModel(_taskService);
            return View(taskLists);
        }

		public ActionResult AddTaskList(string newListName)
		{
			_taskService.AddTaskList(newListName);

			var model = new Models.TaskListsGridModel(_taskService);

			return PartialView("TaskLists", model);
		}

		public ActionResult TasksByListId(int taskListId)
		{
			if (Request.IsAjaxRequest())
			{
				var model = new Models.TasksGridModel(_taskService, taskListId);
				return PartialView("Tasks", model);
			}
			else //if someone just opened an URL like '/Tasks/TasksByListId?taskListId=77' lets bind the tasklistS as well
			{
				var taskLists = new Models.TaskListsGridModel(_taskService);

				var tasksGridmodel = new Models.TasksGridModel(_taskService, taskListId);
				taskLists.SelectedListTasks = tasksGridmodel;

				return View("Index", taskLists);
			}
		}

		public ActionResult AddTask(int taskListId)
		{
			DateTime? dueDate = null;
			try { dueDate = DateTime.Parse(Request.Form["NewTaskDueDate"]); }
			catch { }

			_taskService.AddTask(taskListId, Request.Form["NewTaskSubject"], Request.Form["NewTaskBody"], dueDate);

			var tasksModel = new Models.TasksGridModel(_taskService, taskListId);
			return PartialView("Tasks", tasksModel);
		}

		public ActionResult TaskById(int taskId)
		{
			if (Request.IsAjaxRequest())
			{
				var taskDetailsModel = new Models.TaskDetailsModel(_taskService, taskId);
				return PartialView("TaskDetails", taskDetailsModel);
			}
			else //if someone just opened an URL like '/Tasks/TaskById?taskId=122' lets bind the task as well
			{
				var taskDetailsModel = new Models.TaskDetailsModel(_taskService, taskId);
				var tasksGridmodel = new Models.TasksGridModel(_taskService, taskDetailsModel.TaskListId);
				var taskLists = new Models.TaskListsGridModel(_taskService);

				taskLists.SelectedListTasks = tasksGridmodel;
				tasksGridmodel.SelectedTaskDetails = taskDetailsModel;

				return View("Index", taskLists);
			}
		}

		public ActionResult RefreshTaskFollowers(int taskId)
		{
			var followersModel = new Models.TaskFollowersModel(_taskService, taskId);
			return PartialView("TaskFollowers", followersModel);
		}

		public ActionResult GetFile(int fileId)
		{
			string fileName, mimeType;
			byte[] fileContent;

			_taskService.GetFileById(fileId, out fileName, out mimeType, out fileContent);

			return File(fileContent, mimeType, fileName);
		}

		public ActionResult AddComment(int taskId)
		{
			_taskService.AddComment(Request.Form["newComment"], taskId, Request.Files);
			var commentsModel = new Models.CommentsGridModel(_taskService, taskId);

			if (Request.IsAjaxRequest())
			{
				return PartialView("Comments", commentsModel);
			}
			else
			{
				return TaskById(taskId);
			}
		}

		[HttpGet]
		public ActionResult ShareTaskList(int taskListId)
		{
			var shareModel = new Models.ShareTaskListModel(_taskService, taskListId);
			return View(shareModel);
		}

		[HttpPost]
		public ActionResult ShareTaskList(int taskListId, string emails)
		{
			List<string> emailList = emails.Split(new string[] {","}, StringSplitOptions.RemoveEmptyEntries).ToList();
			_taskService.ShareListWithEmails(taskListId, emailList);

			var shareModel = new Models.ShareTaskListModel(_taskService, taskListId);

			ViewData["message"] = "Success! Return to <a href='/Tasks'>your tasks</a>";

			return View(shareModel);
		}

		public ActionResult DeleteTaskList(int taskListId)
		{
			_taskService.DeleteTaskList(taskListId);
			var taskLists = new Models.TaskListsGridModel(_taskService);
			return PartialView("TaskLists", taskLists);
		}

		public ActionResult DeleteTask(int taskId, int taskListId)
		{
			_taskService.DeleteTask(taskId);
			var tasksModel = new Models.TasksGridModel(_taskService, taskListId);
			return PartialView("Tasks", tasksModel);
		}

		public ActionResult CloseTask(int taskId, int taskListId, FormCollection formCollection)
		{
			_taskService.CloseTask(taskId, formCollection["closed"] == "1");
			var tasksModel = new Models.TasksGridModel(_taskService, taskListId);
			return PartialView("Tasks", tasksModel);
		}

		public string UpdateDueDate(int taskId, DateTime? newDate)
		{
			_taskService.UpdateDueDate(taskId, newDate);
			var taskModel = new Models.TaskDetailsModel(_taskService, taskId);
			return newDate.HasValue ? newDate.Value.ToShortDateString() : "...";
		}

		public void UpdateTask(int taskId, string subject, string body)
		{
			_taskService.UpdateTask(taskId, subject, body);
		}

		public JsonResult GetTaskListUsers(int taskListId)
		{
			return Json(_taskService.GetUsersForTaskList(taskListId), JsonRequestBehavior.AllowGet);
		}

		public void AssignTask(int taskId, int userId)
		{
			_taskService.AssignTask(taskId, userId);
		}
    }
}
